package com.example.myapplication.markwon

import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Rect
import android.text.Layout
import android.text.style.LeadingMarginSpan
import io.noties.markwon.core.MarkwonTheme
import kotlin.math.max
import kotlin.math.min

/**
 * Create by Tanzhenxing on 2025/7/1.
 * Description:
 */
class BlockQuoteSpan(private val theme: MarkwonTheme) : LeadingMarginSpan {
    private val rect = Rect()
    private val paint = Paint()
    override fun getLeadingMargin(first: Boolean): Int {
        return theme.blockMargin
    }

    override fun drawLeadingMargin(
        c: Canvas?,
        p: Paint?,
        x: Int,
        dir: Int,
        top: Int,
        baseline: Int,
        bottom: Int,
        text: CharSequence?,
        start: Int,
        end: Int,
        first: Boolean,
        layout: Layout?
    ) {
        val width = theme.blockQuoteWidth

        paint.set(p)

        theme.applyBlockQuoteStyle(paint)

        val left: Int
        val right: Int
        val l = x + (dir * width)
        val r = l + (dir * width)
        left = min(l.toDouble(), r.toDouble()).toInt()
        right = max(l.toDouble(), r.toDouble()).toInt()

        rect[left, top, right] = bottom

        c!!.drawRect(rect, paint)
    }
}